package handels

import (
	"chef-master/cache"
	"chef-master/models"
	"chef-master/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "信息不可为空",
		})
		return
	}
	var user models.User
	models.DB.Where("username = ?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
		return
	}
	redis_key := "/login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	if pkg.Md5Str(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁两个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录成功",
			"data": user,
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var tap []models.Tap
	redis_key := "/list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&tap)
		jsonData, _ := json.Marshal(tap)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &tap)
	}
	var count int64
	models.DB.Model(&models.Tap{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  500,
		"msg":   "查询成功",
		"data":  tap,
		"count": count,
	})
	return
}
